#!/usr/bin/
#-- coding: utf-8 --
'''
File: MooControllerConn.py
@author: Iván Viguera Cáceres
Last revision: 25/04/2011
Before revision: 27/03/2011
Description:
    Define connector class.
    I modificate and use methos made by Patrick Pollet for basic actions.
    
Credits: 
    (C) Mai 2007 Patrick Pollet <patrick.pollet@insa-lyon.fr>. 
'''
import SOAPpy

class MooControllerConn:
    def __init__(self, wsdl):
        self.proxy = SOAPpy.WSDL.Proxy(wsdl)
        self.user = None
        self.pwd = None
        self.clientId = None
        self.sessionKey = None
        
    def login(self, user = None, pwd = None):
        try:
            if self.user is None or self.pwd is None:
                self.user = user
                self.pwd = pwd
            self.clientId, self.sessionKey = self.proxy.login (self.user, self.pwd);
            return True
        except Exception as e:
            return False
        
    def logout(self):
        if self.clientId is not None:
            self.proxy.logout(self.clientId, self.sessionKey)

    def get_my_courses(self):
        '''
            return a courses list. If user has anyone.
        '''
        res = self.proxy.get_my_courses_byusername(self.clientId,self.sessionKey,self.user)
        return self.force_array(SOAPpy.Types.simplify(res)['courses']['item'])
    
    def get_my_assignment(self):
        '''
            return a assignment list. If user has anyone.
        '''
        res = self.proxy.get_all_assignments(self.clientId,self.sessionKey)
        return self.force_array(SOAPpy.Types.simplify(res)['assignments']['item'])
    
    def force_array(self, object):
        '''
            for some reason SOAPpy convert an array with one item to a simple type
            and Zope do not like later to repeat on it ...
        '''
        if not isinstance(object, type([])):
            return [object]
        return object
    
    def get_list_of_field (self, res, field, sorted=False):
        """
            return a list of all values of field in an array of results
        """
        ret=[]
        for item in res:
            if not item['error']:
                ret = ret+ [item[field]]
        if sorted:
            ret.sort()
        return ret 

if __name__ == "__main__":
    conn = MooControllerConn('http://192.168.1.35/moodle/wspp/wsdl_pp.php')
    if conn.login('profesor', 'Profesor_1'):
        items = conn.get_my_courses()
        print '****Mis cursos:'
        for item in items:
            for key in item.keys():
                print key, ':', item[key]
            print '---------------------'
        
        print '****Tareas asignadas:'
   
        for item in conn.get_my_assignment():
            for key in item.keys():
                print key, ':', item[key]
            print '---------------------'
        
        conn.logout()
        print 'Conexión cerrada con exito'
    else:
        print 'No se ha podido establecer la conexión'